package com.iseastar.guojiang.newcabinet;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Html;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.iseastar.BaseActivity2;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.app.AppCaptureActivity;
import com.iseastar.guojiang.app.Intents;
import com.iseastar.guojiang.cabinet.CabinetParcelsListActivity;
import com.iseastar.guojiang.cabinet.adapter.ServicePointAdapter;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.CabinetBean;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.UserBean;
import com.iseastar.guojiang.station.StationParcelListActivity;
import com.shouhuobao.station.R;

import droid.frame.activity.title.TitleRes;
import droid.frame.view.xlist.SListView;

/**
 * Created by joker on 2018/1/2.
 * 智能柜、快递员负责的所有智能柜列表
 */
public class ServicePointActivity extends BaseActivity2 {
    //顶部驿站和包裹数量html
    private String tipsStr = "<font color=#4a4a4a>当前</font><font color=#D0021B>%1$d</font><font color=#4a4a4a>个驿站，共</font><font color=#D0021B>%2$d</font><font color=#4a4a4a>个包裹待揽收</font>";
    private SListView mListView;
    private ServicePointAdapter mAdapter;
    // 定位相关，传递位置
    private BDLocation mBdLocation;
    // 当前正在操作的
    private CabinetBean.StationCabubetBean clickItem;
    //顶部驿站和包裹数量
    private TextView mHeadTV;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intents.startBaiduLocation(getContext(), null);
    }

    @Override
    public void findViewById() {
        setContentView(R.layout.cabinet_main);
        super.findViewById();
        getAppTitle().setCommonTitle("接收任务");
        mListView = (SListView) findViewById(R.id.listview);
        mHeadTV = (TextView) findViewById(R.id.head_sum_tv);
        mHeadTV.setText("暂无揽收任务");
        // mListView.setFooterDividersEnabled(true);
        mAdapter = new ServicePointAdapter(null, getContext(), mListView);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CabinetBean.StationCabubetBean item = mAdapter.getItem(position);
                clickItem = item;
                AppCache.setCabinetOrStation(item);
                if (item.isStation()) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), AppCaptureActivity.class);
                    intent.setAction(Intents.guojiang_for_station_parcels);
                    startActivityForResult(intent, 101);
                } else {
                    // 跳转到智能柜箱格列表界面
                    Intent intent = new Intent();
                    intent.setClass(getContext(), CabinetParcelsListActivity.class);
                    intent.putExtra("item", item);
                    startActivity(intent);
                }
            }
        });

        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getCabinetData();
            }
        });
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MsgID.location_baidu:// 获取位置
                mBdLocation = (BDLocation) msg.obj;
                mAdapter.setmBdLocation(mBdLocation);
                getCabinetData();
                return false;
            case MsgID.cabinetGetAlls:
                onRefreshComplete();
                cancelLoadingDialog();
                final ReqResult<CabinetBean> result = JSON.parser(msg.obj, CabinetBean.class);
                if (checkLoginStatus(result)) {
                    showToast("刷新成功");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            CabinetBean bean = result.getResult();
                            if (bean != null) {
                                mAdapter.setItems(bean.getItems(), true);
                                if (0 == bean.getParcelCount() || 0 == bean.getStationCount()) {
                                    mHeadTV.setText("暂无揽收任务");
                                } else {
                                    mHeadTV.setText(Html.fromHtml(String.format(tipsStr, result.getResult().getStationCount(), result.getResult().getParcelCount())));
                                }
                            } else {
                                showToast("暂无数据");
                            }
                        }
                    });
                } else {
                    showToast(result.getMessage());
                }
                return true;
            // 通过扫出来的二维码 查询id
            case MsgID.station_getId_by_scancode:
                cancelLoadingDialog();
                final ReqResult<String> result2 = JSON.parser(msg.obj, String.class);
                if (checkLoginStatus(result2)) {
                    checkStationId(result2.getResult());
                } else {
                    showToast(result2.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    /**
     * 验证驿站id是否合法
     *
     * @param id
     */
    private void checkStationId(String id) {
        // 判断id是否合法
        if (id != null && id.equals(clickItem.getId() + "")) {
            Intent intent = new Intent();
            intent.setClass(getContext(), StationParcelListActivity.class);
            startActivity(intent);
            // 通知店老板 裹将来了
            AppHttp.getInstance().stationCourierArrive(clickItem.getSenderPhone());
        } else {
            showToast("驿站编码无效");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 收驿站的包裹
        if (requestCode == 101 && resultCode == Activity.RESULT_OK) {
            String result = data.getStringExtra("result");
            String segment = result;
            if (result.indexOf("/") != -1) {
                segment = result.substring(result.lastIndexOf("/") + 1);
            }
            showLoadingDialog(null);
            AppHttp.getInstance().stationGetId(segment);
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void getCabinetData() {
        UserBean user = AppCache.getUser();
        int userId = user.getId();
        AppHttp.getInstance().cabinetGetAlls(userId);
    }
}
